//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include "servicekit.h"
#include "ipcchannel.h"

#define Lock   do { AuraCriticalSection_Enter(s_hLock); }while(0)
#define Unlock do { AuraCriticalSection_Leave(s_hLock); }while(0)

DLinkNode   CServiceKit::s_serviceKitsList;
Aura_Handle CServiceKit::s_hLock = NULL;

CServiceKit::~CServiceKit()
{
    AuraIpcChannel_Destroy(m_channelId);
    m_pThread->Release();
}

ECode CServiceKit::S_CreateKit(
    Aura_ChannelId  channelId,
    IThread * pThread)
{
    CServiceKit * pKit = new CServiceKit(channelId, pThread);
    if (NULL == pKit) {
        return E_OUT_OF_MEMORY;
    }

    Lock;
    s_serviceKitsList.InsertLast(pKit);
    Unlock;

    return NOERROR;
}

void CServiceKit::S_DeleteKit(
    Aura_ChannelId channelId)
{
    CServiceKit * pKit = NULL;

    Lock;
    ForEachDLinkNode(CServiceKit*, pKit, &s_serviceKitsList)
    {
        if (pKit->m_channelId == channelId) {
             pKit->Detach();
             Unlock;

             delete pKit;
             return ;
        }
    }
    Unlock;

    return;
}

void CServiceKit::S_DeleteAllKits()
{
    Lock;
    while (!s_serviceKitsList.IsEmpty()) {
          CServiceKit * pKit = (CServiceKit *)s_serviceKitsList.Next();
          pKit->Detach();
          delete pKit;
    }
    Unlock;

    return;
}


ECode CServiceKit::S_Create()
{
    s_serviceKitsList.Initialize();
    return AuraCriticalSection_Create(&s_hLock);
}

void CServiceKit::S_Destroy()
{
    AuraCriticalSection_Destroy(s_hLock);
    s_hLock = NULL;

    return;
}


